<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="portal" uri="/WEB-INF/portal.tld" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html lang="zh-CN">
  <head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <%@ include file="/common/plateform/include/common-base.jsp"%>
  <title>权限定义</title>
  <!-- Tell the browser to be responsive to screen width -->
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
</head>

<!-- Part 一、 以下是body主体内容的模块区域 -->
<body class="hold-transition ${sysColor} sidebar-mini">
<div class="wrapper">

  <!-- top start -->
  <%@include file="/common/plateform/top.jsp" %>
  <!-- top end -->
  <!-- left start -->
  <%@include file="/common/plateform/left-project.jsp" %>
  <!-- left end-->

	<div class="content-wrapper">

		<section class="content">
			<div class="row">
				<div class="col-xs-12">
					<div class="box box-success">

						<div class="box-header with-border">
							<h3 class="box-title">  权限定义
								<button class="btn btn-primary" id="btn-add-child" type="button" onclick="toAdd();"><i class="fa fa-plus-circle"></i> 增加子权限</button>
								<button class="btn btn-danger" type="button" onclick="del();">删除</button>
								<button class="btn btn-warning" type="button" onclick="toEdit();">修改</button>
								<button class="btn btn-info" type="button" onclick="refresh();">刷新</button>
							</h3>
							<div class="box-tools pull-right">
								<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
								</button>
							</div>
						</div>


						<div class="box-body">
							<table id="example" class="table tableEdit table-bordered table-hover" >
								<thead class="bg-success">
								<tr>
									<th>名称</th>
									<th>英文标识</th>
									<th>权限地址</th>
									<%--<th>类型</th>--%>
									<th>状态</th>
								</tr>
								</thead>
								<tbody id="actList-body"></tbody>
							</table>
						</div>



					</div>
				</div>
			</div>
		</section>

		<div class="modal fade" id="my_add_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
						<h4 class="modal-title"><font color="red">权限信息</font>&nbsp;<font class="red f14" id="span_act_model_title"></font> </h4>
					</div>
					<div class="modal-body">
						<form class="form-horizontal" role="form" id="actSaveForm">
							<input type="hidden" name="formToken" id="formToken" value="${formToken}"/>
							<input type="hidden" name="pageName" value="uct-act-list"/>
							<input type="hidden" name="formName" value="addForm"/>
							<input type="hidden" name="uctAct.actType" value="menu"/>
							<input type="hidden" name="uctAct.sysEname" value=""/>
							<input type="hidden" name="uctAct.fatherId" class="clean" value="0" data-name="uctAct.fatherId"/>
							<input type="hidden" name="uctAct.w_actId" class="clean" value="" data-name="uctAct.actId"/>
							<input type="hidden" name="uctAct.createTime" class="clean" value="" data-name="uctAct.createTime"/>
							<input type="hidden" name="uctAct.fullCname"  class="clean" data-name="uctAct.fullCname"/>
							<input type="hidden" name="uctAct.fullEname"  class="clean" data-name="uctAct.fullEname"/>

							<div class="box-body">
								<div class="form-group">
									<label class="col-sm-4 control-label">权限标识</label>
									<div class="col-sm-8">
										<input type="text" id="input_uctAct_actEname" class="form-control clean" data-name="uctAct.actEname" name="uctAct.actEname" placeholder="请输入小写英文、数字或下划组成的标识"
											   data-bv-notempty="true" onchange="checkActEname(this)" maxlength="20"
											   data-bv-notempty-message="标识不能为空" data-bv-regexp="true" data-bv-regexp-regexp="^[a-z0-9_-]+$" data-bv-regexp-message="必须是小写英文、数字或下划组成">
									</div>
								</div>
								<div class="form-group">
									<label  class="col-sm-4 control-label" >权限名称</label>
									<div class="col-sm-8">
										<input type="text" class="form-control clean" data-name="uctAct.actCname" name="uctAct.actCname" maxlength="50" placeholder="请输入中文名称" data-bv-notempty="true"  data-bv-notempty-message="名称不能为空">
									</div>
								</div>
								<div class="form-group">
									<label class="col-sm-4 control-label">状态</label>
									<div class="col-sm-8 form-control-static">
										<input type="radio" name="uctAct.actStatus" value="1" checked/>启用
										<input type="radio" name="uctAct.actStatus" value="0" />停用
									</div>
								</div>
								<div class="form-group">
									<label class="col-sm-4 control-label">排序值</label>
									<div class="col-sm-8">
										<input type="text" class="form-control  clean" readonly="readonly" data-name="uctAct.orderNum"  name="uctAct.orderNum" >
									</div>
								</div>
							</div>
							<div class="box-footer">
								<button type="button" class="btn btn-primary pull-left" onclick="mytools.closeModal('my_add_modal');">取消</button>
								<button type="button" class="btn btn-primary pull-right" onclick="saveItem('actSaveForm');">提 交</button>
							</div>
						</form>
					</div>
				</div>
				<!-- /.modal-content -->
			</div>
		</div>


		<script type="text/template" id="dataList">
			<? for ( var i = 0; i < rows.length; i++) {?>
			<tr id=<?=rows[i].uctAct.actId?>  fatherId=<?=rows[i].uctAct.fatherId?>>
				<th style="display:none;"><?=rows[i].uctAct.actId?></th>
				<th style="display:none;"><?=rows[i].uctAct.actCname?></th>
				<th style="display:none;"><?=rows[i].uctAct.fatherId?></th>
				<th style="display:none;"><?=rows[i].uctAct.fullEname?></th>
				<th style="display:none;"><?=rows[i].uctAct.fullCname?></th>
				<?if(rows[i].uctAct.subCount>0||"0"==rows[i].uctAct.fatherId){?>
					<td class="textLeft" id="css_<?=rows[i].uctAct.actId?>" onclick="getChildActsData('<?=rows[i].uctAct.fatherId?>','<?=rows[i].uctAct.actId?>','<?=rows[i].uctAct.fullEname?>',this);">
						<i class="fa fa-plus" ></i>&nbsp;<?=rows[i].uctAct.actCname?>
					</td>
				<?} else{?>
					<td class="textLeft" id="css_<?=rows[i].uctAct.actId?>">
						&nbsp;<?=rows[i].uctAct.actCname?>
					</td>
				<?}?>
				<td class="textLeft">
					<?=rows[i].uctAct.actEname?>
				</td>
				<td class="textLeft">
					<?=rows[i].uctAct.fullEname?>
				</td>
				<td><? if("0"==rows[i].uctAct.actStatus){?><font class="red">停用</font><?}else{?>启用<?}?></td>
			</tr>
			<?}?>
		</script>
		<script>
            var clickMenu= 'user-act-list';
            var actId,orgEname,fatherId,actCname,fullEname,fullCname,isAdd=true;
            var defSysEname = strUtil.doNull(strUtil.getLocalStorage("sysEname"), "");
            $(function () {
                getTableData();
                $('#example tbody').on('click','tr', function (e) {
                    if ( $(this).hasClass('selected') ) {
                        //$(this).removeClass('selected');
                    } else {
                        $('tr.selected').removeClass('selected');
                        $(this).addClass('selected');
                    }
                    actId = $('tr.selected th').eq(0).html();
                    actCname = $('tr.selected th').eq(1).html();
                    fatherId = $('tr.selected th').eq(2).html();
                    fullEname = $('tr.selected th').eq(3).html();
                    fullCname = $('tr.selected th').eq(4).html();
                } );
            });
            //设置模态框隐藏事件钩子
            $( '#my_modal' ).on( 'hide.bs.modal' ,function(e){
                cleanData('userFormData');
            });


            function getTableData(){
                $("#actList-body").html("");
                var index_load = layer.load(1, {shade: false});
                $.ajax({type:'get',
                    url:common_list_url,
                    // data:{'id':'0','doCode':'treeAct'},
                    data:{'pageName':'uct-act-list','formName':'searchForm','uctAct.w_sysEname':defSysEname,'uctAct.w_fatherId':'0'},
                    dataType:'json',
                    success: function(myData){
                        console.log("myData",myData);
                        layer.close(index_load);
                        if(myData.total>0){
                            var data = baidu.template('dataList',eval(myData));
                            $("#actList-body").html(data);
						}else{
                            //没数据，就补充一个：初始化按钮
                            if(!strUtil.isNull(defSysEname) && ($("#btn-init-sysmodule").length==0) ){
                                var btnInitHtml ="<button id='btn-init-uctActData' class='btn btn-warning' type='button' onclick=\"addInitSysAct();\"><i class='fa fa-code'></i> 初始化数据</button>&nbsp;";
                                $("#btn-add-child").before(btnInitHtml);
                            }else{
                                $("#btn-init-uctActData").remove();
							}
                        }
                    }
                });
            }

            //初始化
            function addInitSysAct(){
                var msg_load = layer.msg("正在初始化系统权限，请耐心等待...");
                var paramData = {};
                paramData["pageName"]="uct-act-add";
                paramData["formName"]="addForm";
                paramData["uctAct.fatherId"]="0";
                paramData["uctAct.sysEname"]=defSysEname;//所属工程
                paramData["uctAct.actEname"]=defSysEname;
                paramData["uctAct.actCname"]=strUtil.doNull(strUtil.getLocalStorage("sysCname"), "");
                paramData["uctAct.fullEname"]="/"+paramData["uctAct.actEname"];
                paramData["uctAct.fullCname"]="/"+paramData["uctAct.actCname"];
                paramData["uctAct.actType"]="menu";
                paramData["uctAct.actStatus"]="1";
                paramData["uctAct.orderNum"]="1";
                paramData["uctAct.createTime"]=new Date().getTime();
                $.ajax({
                    type:"post",url:common_submit_url,data: paramData,dataType:"json",async:false,
                    success: function(myData){
                        console.log(myData);
                        if(myData.flag=="T" && !strUtil.isNull(myData.ids)){
                            layer.close(msg_load);
                            $("#btn-init-uctActData").remove();
                            refresh();
                        }else{
                            layer.alert("初始化菜单数据，操作失败");
                        }
                    }
                });
            }
            function toAdd(){
                if(strUtil.isNull(actId)){
                    layer.alert("请先选中一条数据！");
                    return;
                }
                isAdd=true;
                var nextCount = getChildCount(actId);
                mytools.cleanData("#actSaveForm");
                $("#span_act_model_title").text("[上一级："+fullCname+"]");
                $('#my_add_modal').modal('show');
                $("#actSaveForm").find("input[name='formName']").val("addForm");
                $("#actSaveForm").find("input[name='uctAct.fatherId']").val(actId);
                $("#actSaveForm").find("input[name='uctAct.orderNum']").val((nextCount+1));
                $("#actSaveForm").find("input[name='uctAct.sysEname']").val(defSysEname);
                initRadio("uctAct.actType","menu");
                initRadio("uctAct.actStatus","1");
                // $("#data_actEname").attr("readonly",false)
				// ;
            }

            function toEdit(){
                //$('#actSaveForm').reset();
                if(strUtil.isNull(actId)){
                    layer.alert("请先选中一条数据！");
                    return;
                }else{
                    isAdd=false;
                    mytools.cleanData("#actSaveForm");
                    $("#span_act_model_title").text("[上一级："+fullCname+"]");
                    $("#actSaveForm").find("input[name='formName']").val("editForm");
                    $.ajax({ type:'get', url:common_info_url,dataType:'json',
                        data:{"pageName":"uct-act-list","formName":"searchForm","uctAct.w_actId":actId},
                        success: function(myData){
                            console.log(myData);
                            FormUtil.loadView("uctAct", myData["uctAct"]);
                            $('#my_add_modal').modal('show');
                            initRadio("actType",myData.actType);
                            initRadio("actStatus",myData.actStatus);
                        }
                    });
                }
                //$('#my_modal').modal('show');
            }

            function getChildCount(fatherId) {
                var total = 0;
                $.ajax({ type:'get', url:common_list_url,dataType:'json',async:false,
                    data:{"pageName":"uct-act-list","formName":"searchForm","uctAct.w_fatherId":fatherId},
                    success: function(myData){
//                        console.log(myData);
                        total = myData.total;
                    }
                });
                return total;
            }

            function checkActEname(obj) {
				//校验标识是否重复
				var flag = false;
				var thisActEname = $(obj).val();
				if(strUtil.isNull(thisActEname)){
				    return;
				}
                var thisActId = $("#actSaveForm").find("input[name='uctAct.w_actId']").val();
                $.ajax({ type:'get', url:common_list_url,dataType:'json',
                    data:{"pageName":"uct-act-list","formName":"searchForm","uctAct.w_sysEname":defSysEname,"uctAct.w_actEname":thisActEname},
                    success: function(myData){
                        if(myData.total>0){
//                            console.log(myData);
                            var hisId = myData.rows[0].uctAct.actId;
                            if(!strUtil.isNull(thisActId) && hisId==thisActId){
                                //修改时若是自己则认为不重复
                                flag=false;
                            }else{
                                flag = true;
                                layer.tips('标识['+thisActEname+']已存在，请更换！', '#'+$(obj).attr("id"), {tips: 1});
                                $(obj).val("");
                            }
                        }
                    }
                });
            }
            function saveItem(formId){
                var validate = $('#'+formId).data('bootstrapValidator').validate();
                if(!validate.isValid()){ //如果校验不通过就返回
                    return;
                }
                var thisFatherId = $("#"+formId).find("input[name='uctAct.fatherId']").val();
                var thisActEname = $("#"+formId).find("input[name='uctAct.actEname']").val();
                var thisActCname = $("#"+formId).find("input[name='uctAct.actCname']").val();
                if(isAdd){
                    $("#"+formId).find("input[name='uctAct.createTime']").val(new Date().getTime());
                    $("#"+formId).find("input[name='uctAct.fullEname']").val(fullEname+"/"+thisActEname);
                    $("#"+formId).find("input[name='uctAct.fullCname']").val(fullCname+"/"+thisActCname);
                }else{
                    $("#"+formId).find("input[name='uctAct.fullEname']").val(fullEname.substring(0,fullEname.lastIndexOf("/")+1)+thisActEname);
                    $("#"+formId).find("input[name='uctAct.fullCname']").val(fullCname.substring(0,fullCname.lastIndexOf("/")+1)+thisActCname);
				}

                var index_submit = layer.confirm('您确定要保存信息吗？', {btn: ['Yes','No'],closeBtn: 0,offset: '220px'}
                    , function(){
                        var index_load = layer.load(1, {shade: false});
                        $.ajax({ type:'post', url:common_submit_url,dataType:'json',
                            data:$("#"+formId).serialize(),
                            success: function(myData){
                                setToken();
                                if(myData.flag=='T'){
                                    if(isAdd){
                                        var childCount = getChildCount(thisFatherId);
                                        $.ajax({ type:'post',url:common_submit_url,dataType:'json',
                                            data:{'pageName':'uct-act-list','formName':'editForm','uctAct.subCount':childCount,'uctAct.w_actId':thisFatherId},
                                            success: function(myData){layer.close(index_load);}
                                        });
									}
                                    layer.alert("操作成功！");
                                    $('#my_add_modal').modal('hide');
                                    refresh();
                                }else{
                                    layer.alert("操作失败："+myData.msg);
								}
                            }
                        });
                    });
            }

            function del(){
                if(strUtil.isNull(actId)){
                    layer.alert("请先选中一条数据！");
                    return;
                }else{
                    if(fullEname=='/plateform'){
                        layer.alert("平台根权限不能删除！");
                        return;
                    }
                    if(getChildCount(actId)>0){
                        layer.alert("存在子元素，无法删除！");
                        return;
					}
                    var index_submit = layer.confirm("您确定要删除["+actCname+"]吗？", {btn: ["Yes","No"],closeBtn: 0,offset: "220px"}
					, function() {
						layer.close(index_submit);
                            var index_load = layer.load(1, {shade: false});
                            $.ajax({ type:'post',url:common_submit_url,dataType:'json', data:{'pageName':'uct-act-list','formName':'delForm','uctAct.w_actId':actId},
                                success: function(myData){
                                    layer.alert(myData.msg, { closeBtn: 0 });
                                    if(myData.flag=='T'){
                                        var childCount = getChildCount(fatherId);
                                        $.ajax({ type:'post',url:common_submit_url,dataType:'json',
                                            data:{'pageName':'uct-act-list','formName':'editForm','uctAct.subCount':childCount,'uctAct.w_actId':fatherId},
                                            success: function(myData){layer.close(index_load);}
                                        });
                                        refresh();
                                    }
                                }
                            });
					});
                }
            }

            function cannel(modalId){
                $("input[type=reset]").trigger("click");
                $('#'+modalId).modal('hide');
            }


            function refresh(){
                actId="",actCname="";
                getTableData();
            }

            function getChildActsData(fatherId,actId,treeLevel,obj){
                // alert(fatherId+"------"+actId+"------"+treeLevel+"------"+obj)
                var count =0;
                var ss = treeLevel.split("/");
                count = ss.length-1;
                $.ajax({ type:'get',url:common_list_url,
                    // data:{'id':actId,'doCode':'treeAct','actId':actId},
                    data:{'pageName':'uct-act-list','formName':'searchForm','uctAct.w_fatherId':actId,'orderBy':'uctAct.order_num'},
                    dataType:'json',
                    success: function(myData){
                        console.log(myData);
                        // var data = baidu.template('dataList',myDatas);
                        var data = baidu.template('dataList',myData);
                        if($(obj).find("i").hasClass("fa-minus")){
                            $(obj).find("i").attr("class","fa fa-plus"); delActsChiled(actId);
                        }else{
                            $(obj).find("i").attr("class","fa fa-minus");
                            $("#"+actId).after(data);
                            $("[fatherid='"+actId+"']").each(function(i){
                                var thisObj = $(this);
                                var pd = "10px 20px 10px ";
                                var num = pd+(count*20)+"px";
                                $(thisObj).find("td").eq(0).css("padding",num);
                            });
                        }
                    }
                });
            }
            function delActsChiled(id){
                $("[fatherid='"+id+"']").each(function(i){
                    var thisObj = $(this);
                    $(thisObj).remove();
                    var id = thisObj.attr("id");
                    delActsChiled(id);
                });
            }

            function uPssOrN(flag){
                if(flag == 'Y'){
                    $('#data_actUrl').attr("required","true");
                    $('.isupdPass').show();
                }else if(flag == 'N'){
                    $('#data_actUrl').attr("required","false");
                    $('.isupdPass').hide();
                }
            }
            function initRadio(elemname,selVl){
                var myobj=document.getElementsByName(elemname);
                if(myobj==null)return;
                for ( var i = 0; i < myobj.length; i++) {
                    if (myobj[i].value == selVl) {
                        myobj[i].checked = "true";
                    }
                }
            }
            function setToken(){
                $.ajax({ type:'get',url:'${ctx}/sendPage/token?token=true',dataType:'text',async:false,
                    success: function(myData){ $('#formToken').val(myData);	}
                });
            }

            function setValidate(id){
                $(id).each(function(){
                    $(this).bootstrapValidator({
                        feedbackIcons: {
                            valid: 'glyphicon glyphicon-ok',
                            invalid: 'glyphicon glyphicon-remove',
                            validating: 'glyphicon glyphicon-refresh'
                        },/** 以下需要结合实际业务清空补充个表单元素的验证规则 **/
                        fields:{
                            /** 可自定义新增验证规则
                             "uctUser.userEname":{
		    		 validators: {
		    			 regexp: {
		    				 regexp: /^[0-9]+$/,
		                      message: '只能是数字'
		                  }
		              }
		    	}
                             **/
                        }
                    });
                });
            }

            $(".modal").on('shown.bs.modal', function () {
                $(this).find("form").each(function(){
                    var formId = $(this).attr("id");
                    if(!strUtil.isNull(formId)){
                        formId="#"+formId;
                        setValidate(formId);//定义add表单验证属性
                        mytools.cleanValidate(formId);//清空上次校验规则提示
                    }
                });
            });

		</script>


		<!-- Main end -->
	</div>
</div>

<!-- /.content-wrapper -->
<!-- foot start -->
<%@include file="/common/plateform/foot.jsp" %>
<!-- foot start -->
</body>
</html>

